import React, { useEffect, useRef, useState } from 'react'
import { Card, Button, Table, Space, Modal, Form, Input, Select } from "antd"
import { getAllCategoryApi, addCategoryApi } from "../../../apis/categoryApi"

const { Option } = Select

const layout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 4,
    span: 16,
  },
};

export default function Category() {
  const [dataSource, setDataSource] = useState([])
  const [parentId, setParentId] = useState(0)
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [isShow, setIsShow] = useState(false)
  const [parentData, setParentData] = useState([])
  useEffect(() => {
    fetchData()
  }, [parentId])

  //项目中要发送请求，都是需要提供一个函数
  //尽量不要直接useEffect中发送请求
  const fetchData = async () => {
    const res = await getAllCategoryApi({ parentId })
    setDataSource(res.data.data.data)
  }

  const deleteRow = () => {
    console.log("删除");
  }
  const findSubsCategory = (val) => {
    console.log(val);
    setParentId(val._id)
  }
  const back = () => {
    setParentId(0)
  }


  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const onFinish = (values) => {
    
    values.parentId = values.parentId?values.parentId:0
    console.log(values);
  };
  const onFinishFailed = (values) => {
    console.log(values);
  }

  const selectTypeValueEvent = (value) => {
    console.log(value);
    if (value == "一级分类") {
      setIsShow(false)
    } else {
      setIsShow(true)
    }
  }
  const openModel = async () => {
    setIsModalOpen(true)
    if (parentData.length == 0) {
      const res = await getAllCategoryApi({ parentId: 0 })
      setParentData(res.data.data.data)
    }
  }


  const columns = [
    {
      title: '分类名字',
      dataIndex: 'name',
      align: "left",
      width: "30%"
    },
    {
      title: '分类类型',
      dataIndex: 'type'
    },
    {
      title: '操作',
      render: (p1, p2) => {
        return (
          <Space>
            {parentId == 0 ? <Button onClick={() => findSubsCategory(p1)}>子分类</Button> : null}
            <Button onClick={deleteRow} type='primary'>删除</Button>
          </Space>
        )
      }
    },
  ];

  return (
    <>
      <Card
        size="default"
        title={parentId == 0 ? "商品分类" : <Button onClick={back}>返回</Button>}
        extra={<Button onClick={openModel}>添加分类</Button>}
        style={{
          width: "100%",
        }}
      >
        <Table
          dataSource={dataSource}
          columns={columns}
          bordered={true}
          loading={false}
          rowKey="_id"
          pagination={{ defaultCurrent: 1, defaultPageSize: 6, showQuickJumper: true, showSizeChanger: true, pageSizeOptions: [6, 12, 18] }}
        />
      </Card>
      <Modal title="添加分类" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form
          {...layout}
          name="control-hooks"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          style={{
            maxWidth: 600,
          }}
        >
          <Form.Item
            name="name"
            label="分类名字"
            rules={[
              {
                required: true, message: "分类名字不能为空"
              },
              // {
              //   min:3,message:"长度最小为3"
              // },
              // {
              //   max:10,message:"最长内容不超过10个"
              // },
              {
                pattern: /^[0-9a-zA-Z\u4e00-\u9fa5]{3,8}$/, message: "必须字母数字3-8位"
              }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="type"
            label="分类类型"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Select
              placeholder="请选中分类类型"
              allowClear
              onChange={selectTypeValueEvent}
            >
              <Option value="一级分类">一级分类</Option>
              <Option value="二级分类">二级分类</Option>
            </Select>
          </Form.Item>
          {isShow ? <Form.Item
            name="parentId"
            label="父级分类"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Select
              placeholder="请选中父级分类"
              allowClear
            >
              {parentData.map(item=>{
                return <Option key={item._id} value={item._id}>{item.name}</Option>
              })}
            </Select>
          </Form.Item> : null}

          <Form.Item {...tailLayout}>
            <Space>
              <Button type="primary" htmlType="submit">
                添加
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
